
#Implments Generalized Synthetic Control by Xu (2017)
#The R implementation can be found here: https://yiqingxu.org/software/gsynth/gsynth_examples.html.
#We follow the code in the examples by Xu and Liu (Mar 6, 2020) to implement the model. 


rm(list = ls())
data=readRDS('.............../v1_apr13data.rds')
data=subset(data,!province=='Alaska')
data=subset(data,!province=='American Samoa')


# imports libraries 
library(gsynth)
library(panelView)

#makes it R data frame
data=data.frame(data)

#visualizes treatment status
panelView(gr_case~D,data =data, index = c("province","Date"),ylab="State",pre.post = TRUE,
          theme.bw=TRUE,axis.adjust=TRUE) 



#two way fixed effect + parametric
set.seed(123)
result1=gsynth(gr_case~D+fd, data=data,index= c("province","Date"), 
               force = "two-way",CV = TRUE,r=c(1, 5), se=TRUE, 
               inference = "parametric", nboots= 1000, parallel= FALSE)

result1$est.avg 
result1

#plot
plot(result1, type = "counterfactual",axis.adjust=TRUE,
     raw = "none", main="", theme.bw=TRUE)

plot(result1, theme.bw=TRUE)


#unit fixed effect + parametric
set.seed(1234)
result2=gsynth(gr_case~D+fd, data=data,index= c("province","Date"), 
               force = "unit",CV = TRUE,r=c(1, 5), se=TRUE, 
               inference = "parametric", nboots= 1000, parallel= FALSE)

result2$est.avg 
result2

result2$Ntr
result2$Nco

#plot
plot(result2, type = "counterfactual",axis.adjust=TRUE,
     raw = "none", main="")


#time fixed effect + parametric
set.seed(1235)
result3=gsynth(gr_case~D+fd, data=data,index= c("province","Date"), 
               force = "time",CV = TRUE,r=c(1, 5), se=TRUE, 
               inference = "parametric", nboots= 1000, parallel= FALSE)

result3$est.avg
result3

#plot
plot(result3, type = "counterfactual",axis.adjust=TRUE,
     raw = "none", main="")


